#!/usr/bin/env python
# -*- coding: latin-1 -*-

import sys
from time import sleep
from vista.Menu import *
from modelo.batalla_naval import Posicion
from PodSixNet.Connection import connection, ConnectionListener

class BatallaClient(ConnectionListener):
	def __init__(self, host, port, passwd, nick, tablero=None, turno=False):
		self.Connect((host, port))
		self.tablero = tablero
		self.nickname = nick
		self.menu = Menu()
		self.listo = False
		self.tupla = None
		self.valor = None
		self.esperarRespuesta = False
		self.turno = host == "127.0.0.1"
		if self.turno:
			self.turno = turno
		self.verAtaque = False
		connection.Send({"action":"nickname", "nickname": self.nickname, "passwd":passwd})
	
	def Loop(self):
		self.Pump()
		connection.Pump()
	
	def Atacar(self, tupla):
		self.esperarRespuesta = True
		connection.Send({"action":"ataque", "ataque": tupla, "quien": self.nickname})

	def Network_ataque(self, data):
		self.verAtaque = True
		self.tupla = data["ataque"][0], data["ataque"][1]
		pos = Posicion(int(data["ataque"][0]), int(data["ataque"][1]))
		self.valor = self.tablero.disparar(pos)
		if self.tablero.estanTodosHundidos():
			connection.Send({"action": "respuesta", "ataque": data["ataque"],\
				 "respuesta": self.valor, "quien": self.nickname, "fin" : 0})
			self.menu.popup("PERDISTE", "lo lamento, pero perdiste")
			sleep(5)
			sys.exit(0)			
		connection.Send({"action": "respuesta", "ataque": data["ataque"], "respuesta": self.valor, "quien": self.nickname})
		
	def Network_respuesta(self, data):
		self.listo = True
		try:
			fin = data["fin"]
			self.menu.popup("GANASTE!!!", "felicitaciones, ganaste")
			fin += 4
			sleep(5)
			sys.exit(0)
		except:
			pass
		self.ultimaTupla = data["ataque"]
		self.ultimoValor = data["respuesta"]

	def Network_connected(self, data):
		pass
	
	def Network_error(self, data):
		connection.Close()
		self.menu.popup("Error", data['error'][1])
		sys.exit(1)

	def Network_refused(self, data):
		connection.Close()	
		self.menu.popup("Error", data['msj'])
		sys.exit(1)

	def Network_disconnected(self, data):
		connection.Close()	
		self.menu.popup("Status", 'Server disconnected')
		sys.exit(1)

